var firstTime = 0;
var language = "python";

var pathName = window.location.pathname;
var jqueryFileTreePyDirListFn =  "/python_scripts/jqueryFileTree/jqueryFileTree.py/dirlist";
var url = window.location;
var modPythonGetFileContentsFn = url + "python_scripts/mod_python/mod_python.py/getFileContents";

var modPythonCreateFileFn = url + "python_scripts/mod_python/mod_python.py/createFile";

var modPythonWriteToFileFn = url + "python_scripts/mod_python/mod_python.py/writeToFile";

var modPythonDeleteFileFn = url + "python_scripts/mod_python/mod_python.py/deleteFile";

var modPythonExecuteCodeFn = url + "python_scripts/mod_python/mod_python.py/executeCode";

var userScriptsFolder = "user_scripts";

var lang = {};

lang['py'] = "python";
lang['pl'] = "perl";
lang['rb'] = "ruby";
lang['sh'] = "bash";

var filetreeLoc;
var fileSelected = "";
var globalEditor;
var existingTabs = new Array(5);

function chomp(data) {
	return data.replace(/0$/, "");
}
function rightButtonClicked(file) {
	parent.fileSelected = file;
	setLanguage(parent.fileSelected);
}


function executeFile(fileName, lang)
{
	if ((typeof(fileName) == "undefined") || (fileName == ""))
	{
		fileName = fileSelected;
	}

	if ((typeof(lang) == "undefined") || (lang == ""))
	{
		lang = parent.language;
	}

	var resultsLoc = $("#resultsFrame").contents().find("#results");
	$.ajax({ type: "POST",
		url: parent.modPythonExecuteCodeFn,
		data: ({'fileName' : fileName, 'language' : language}),
		dataType: "text",
		async: false,
		cache: false,
		success: function(data, textStatus, XMLHttpRequest)
		{
 			$(resultsLoc).val(chomp(data));
		}
	});
}

function createFile(fileName)
{
	var operation = 0;
	if ((typeof(fileName) == "undefined") || (fileName == ""))
	{
		return false;
	}

	$.ajax({ type: "POST",
    		url: parent.modPythonCreateFileFn,
		cache: false,
		data: ({'filePath' : fileName}),
		success: function(response)
		{
		}
	});

}

function deleteFile(fileName) 
{
	if ((typeof(fileName) == "undefined") || (fileName == ""))
	{
		fileName = parent.fileSelected;
	}

    	$.ajax({ type: "POST",
		url: parent.modPythonDeleteFileFn,
		cache: false,
		data: ({'filePath' : fileName}),
		success: function(response)
		{
		}
	});
}

function getFileContents(fileName)
{
	var answerLoc = parent.globalEditor.getSession();
	if ((typeof(fileName) == "undefined") || (fileName == ""))
	{
		fileName = parent.fileSelected;
	}
	$.ajax({ type: "POST",   
		url: parent.modPythonGetFileContentsFn,
		data: ({'fileName' : fileName}),
		async: false,
		cache: false,
		success : function(data, textStatus, XMLHttpRequest)
		{
  			answerLoc.setValue(chomp(data));
		}
	});
}	

function setLanguage(file) {
	var extn = file.split(".");
	extn = extn[extn.length - 1];
	parent.language = lang[extn];
}

function fileClicked(file) {
	fileSelected = file;
	getFileContents();
	setLanguage(parent.fileSelected)
}


function basename (path) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Lincoln Ramsay
    // +   improved by: djmix
    // *     example 1: basename('/www/site/home.htm', '.htm');
    // *     returns 1: 'home'
    // *     example 2: basename('ecra.php?p=1');
    // *     returns 2: 'ecra.php?p=1'
    if (language == "python") {
	  suffix = ".py";
    }
    
    var b = path.replace(/^.*[\/\\]/g, '');

    if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix) {
        b = b.substr(0, b.length - suffix.length);
    }

    return b;
}

//
// Response sends status as 0 appended to data, which should be chomped
// This is a workaround, will be changed later
//


function writeToFile(fileName, content)
{

	var currentCode = "";
	if (typeof(fileName) == "undefined")
	{
		fileName= parent.fileSelected;
	}

	if (typeof(content) == "undefined")
	{
		var answerLoc = parent.globalEditor.getSession();
		currentCode = answerLoc.getValue();
	} else {
		currentCode = content;
	}
	var b64Code = encode64(currentCode);

	$.ajax({ type: "POST",   
		url: parent.modPythonWriteToFileFn,
		data: ({'filePath' : fileName, 'fileContent' : b64Code}),
		async: false,
		success : function(data, textStatus, XMLHttpRequest)
		{
			switch(data)
			{
				case "_FILE_CREATE_ERROR":
					alert("File Creation Error");
					break;
				case '_FILE_WRITE_ERROR':
					alert("Error writing to file");
					break;
				default:
					getFileContents();
			}
		}
	});
	setLanguage(parent.fileSelected);
}

function submitButtonPressed()
{
	// Code to handle what to do when submit button is pressed
}

function answerAreaClicked()
{
	var answerLoc = parent.globalEditor.getSession();
	var resultsLoc = $("#resultsFrame").contents().find("#results");
	if (firstTime == 0) 
	{
		$(answerLoc).text("");
		firstTime = 1;	
	}
	$(resultsLoc).fadeTo('slow', 0.8);
	return true;
}

function resultAreaClicked()
{
	var answerLoc = parent.globalEditor.getSession();
	//$(answerLoc).fadeTo('slow', 0.3);
	$(resultsLoc).fadeTo('slow', 1.0);
	return true;
}

